package com.jijuxie.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jijuxie.common.exception.ServiceException;
import com.jijuxie.common.utils.SecurityUtils;
import com.jijuxie.system.domain.SysUser;
import com.jijuxie.system.domain.SysUserRole;
import com.jijuxie.system.mapper.SysUserMapper;
import com.jijuxie.system.mapper.SysUserRoleMapper;
import com.jijuxie.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.dev33.satoken.stp.StpUtil;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Override
    public SysUser selectUserByUsername(String username) {
        return baseMapper.selectUserByUsername(username);
    }

    @Override
    public SysUser selectUserById(Long userId) {
        return baseMapper.selectUserById(userId);
    }

    /**
     * 重写getById方法，使用selectUserById代替默认的selectById以避免字段映射问题
     */
    @Override
    public SysUser getById(java.io.Serializable id) {
        if (id instanceof Long) {
            return this.selectUserById((Long) id);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(SysUser user) {
        if (!checkUsernameUnique(user.getUsername())) {
            throw new ServiceException("用户名已存在");
        }
        // 密码加密
        SecurityUtils.validatePassword(user.getPassword());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        // 设置默认状态
        user.setStatus("0");
        user.setDelFlag("0");
        save(user);

        // 设置默认角色
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(user.getUserId());
        userRole.setRoleId(2L); // 假设2是普通用户角色ID
        userRoleMapper.insert(userRole);
    }

    @Override
    public boolean checkUsernameUnique(String username) {
        return count(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username)) == 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(Long userId, String password) {
        SecurityUtils.validatePassword(password);
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setPassword(SecurityUtils.encryptPassword(password));
        updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(SysUser user) {
        // 不允许修改用户名和密码
        user.setUsername(null);
        user.setPassword(null);
        updateById(user);
    }

    @Override
    public String login(String username, String password) {
        // 查询用户
        SysUser user = selectUserByUsername(username);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        // 校验密码
        if (!SecurityUtils.matchesPassword(password, user.getPassword())) {
            throw new ServiceException("密码错误");
        }

        // 校验状态
        if ("1".equals(user.getStatus())) {
            throw new ServiceException("账号已停用");
        }

        // 登录
        StpUtil.login(user.getUserId());
        return StpUtil.getTokenValue();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePassword(Long userId, String oldPassword, String newPassword) {
        // 校验旧密码
        SysUser user = getById(userId);
        if (!SecurityUtils.matchesPassword(oldPassword, user.getPassword())) {
            throw new ServiceException("原密码错误");
        }

        // 校验新密码
        SecurityUtils.validatePassword(newPassword);

        // 更新密码
        user.setPassword(SecurityUtils.encryptPassword(newPassword));
        updateById(user);
    }
}
